package com.ruoyi.service;

import com.ruoyi.bole.integral.domain.BoleIntegralApplication;
import com.ruoyi.bole.integral.service.IBoleIntegralApplicationService;
import com.ruoyi.bole.integral.service.IBoleIntegralSeasonService;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.domain.ProcessInstanceInfo;
import com.ruoyi.domain.TaskDTO;
import com.ruoyi.remark.domain.BoleRemarkProject;
import com.ruoyi.remark.service.IBoleRemarkProjectService;
import org.camunda.bpm.engine.RuntimeService;
import org.camunda.bpm.engine.TaskService;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.camunda.bpm.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ProcessServiceImpl implements ProcessService{
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private IBoleRemarkProjectService boleRemarkProjectService;
    @Autowired
    private IBoleIntegralSeasonService boleIntegralSeasonService;
    @Autowired
    private IBoleIntegralApplicationService boleIntegralApplicationService;

    @Transactional
    @Override
    public int startProcessForIntegral(BoleIntegralApplication boleIntegralApplication, String processKey) {
        //如果applyDate为空就赋值现在
        if (boleIntegralApplication.getApplyDate() == null) {
            boleIntegralApplication.setApplyDate(new Date());
        }
        //赋予赛季
        boleIntegralApplication.setSeasonId(boleIntegralSeasonService.selectMaxSeason());
        // 获取当前登录用户的 userid
        Long userId = SecurityUtils.getUserId();
        boleIntegralApplication.setUserId(userId);
        boleIntegralApplicationService.insertBoleIntegralApplication(boleIntegralApplication);


        Map<String, Object> variables = new HashMap<>();
        variables.put("integralId", boleIntegralApplication.getId());

        // 直接调用，不捕获异常
        try{
            runtimeService.startProcessInstanceByKey(processKey, variables);
        }catch (Exception e){
             System.out.println("流程启动失败：" + e.getMessage());
        }


        return 1; // 只有成功才会返回
    }

    @Transactional
    @Override
    public int startProcess(BoleRemarkProject boleRemarkProject, String processKey) {
        boleRemarkProjectService.insertBoleRemarkProject(boleRemarkProject);
        Map<String, Object> variables = new HashMap<>();
        variables.put("remarkId", boleRemarkProject.getSubmitId());

        // 直接调用，不捕获异常
        runtimeService.startProcessInstanceByKey(processKey, variables);

        return 1; // 只有成功才会返回
    }

    @Override
    public List<TaskDTO> getRunningProcessInstances(String assignee) {
        // 查询原始任务列表
        List<Task> tasks = taskService.createTaskQuery()
                .taskAssignee(assignee)
                .list();
        return tasks.stream().map(task -> {
            TaskDTO dto = new TaskDTO();
            dto.setId(task.getId());
            dto.setName(task.getName());
            dto.setAssignee(task.getAssignee());
            dto.setCreateTime(task.getCreateTime());

            // 获取流程实例ID（通过任务获取流程实例ID）
            String processInstanceId = task.getProcessInstanceId();

            // 通过流程实例ID获取流程变量（包括dataId）
            Map<String, Object> variables = runtimeService.getVariables(processInstanceId);
            Long dataId = (Long) variables.get("remarkId"); // 提取业务数据ID
            dto.setRemarkId(dataId); // 将dataId存入DTO

            return dto;
        }).collect(Collectors.toList());
    }

    public String completeTask(@RequestParam("taskId") String taskId,
                               @RequestParam Map<String, Object> variables) {
        taskService.complete(taskId, variables);
        return "任务完成";
    }
}
